﻿using System;
using System.ComponentModel.Design;
using Microsoft.VisualStudio.Shell;
using PS_WSSDeploy_Package.Application;
using PS_WSSDeploy_Package.Settings;
using PS_WSSDeploy_Package.Utils;

namespace PS_WSSDeploy_Package.WdCommand
{
    class CopyToRootCmd : BaseCmd, IWdTask
    {
        public static BaseCmd Create(OleMenuCommandService service, bool enableForSandbox)
        {
            var instance = new CopyToRootCmd();
            var cmdId = new CommandID(GuidList.guidPS_WSSDeploy_PackageCmdSet, (int)PkgCmdIDList.cmdidCopyToRootCommand);
            AddCommandToMenu(service, instance, cmdId, enableForSandbox);
            return instance;
        }

        public override void DoExecute()
        {
            AddTask(this);
        }

        public void TaskExecute()
        {
            try
            {
                var rootFiles = SharePointProjectManager.GetRootFiles(ProjectName);
                if (rootFiles.Count > 0)
                {
                    SharePointProjectManager.ReplaceToken(SpFileToken.ProjectAssemblyFullName, ProjectAssemblyFullName, rootFiles);
                    Cc.CopyToRoot(rootFiles);
                    WriteOutput(string.Format(WssDeployResources.CopyToRootCmd_CopyToRootSucceeded, ProjectName));
                }
                else
                {
                    if (string.IsNullOrEmpty(RootFolder))
                    {
                        throw new ApplicationException(WssDeployResources.CopyToRootCmd_ProjectNotContainSharePointRootFolder);
                    }
                    Cc.CopyToRoot(RootFolder, RootFolderPath);
                    WriteOutput(string.Format(WssDeployResources.CopyToRootCmd_CopyToRootSucceeded, RootFolderPath));
                }
                SetSuccess();
            }
            catch (Exception ex)
            {
                WriteOutput(string.Format(WssDeployResources.CopyToRootCmd_CopyToRootSucceeded, ex.Message));
                SetFailed();
            }
        }
    }
}
